package com.jb.workflow.app.bean;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.jb.workflow.app.client.WfUtil;

import net.oschina.app.AppException;
import net.oschina.app.bean.Entity;
import net.oschina.app.bean.Tweet;
import net.oschina.app.common.StringUtils;

/**
 * todo列表实体类
 * @author ericwong
 * @version 1.0
 * @created 2014-12-5
 */
public class TodoList extends Entity {
	
	private List<TodoTask> todoList = new ArrayList<TodoTask>();
	
	public List<TodoTask> getTodolist() {
		return todoList;
	}
	
	public static TodoList parse(InputStream inputStream, final int catalog) throws IOException, AppException {
		
		TodoList todo = new TodoList();
		TodoTask task;
		
		String result = StringUtils.toConvertString(inputStream);
		
		try {
			JSONObject object = new JSONObject(result);
			if (object != null) {
				JSONArray arr = (JSONArray) object.get("data");
				for (int i = 0; i < arr.length(); i++) {
					JSONObject taskObj = (JSONObject) arr.get(i);
					if (taskObj != null) {
						task = new TodoTask();
						task.setId(taskObj.getInt("id"));
						if (!taskObj.isNull("assignee")) {
							task.setAuthor(taskObj.getString("assignee"));
						}
						if (!taskObj.isNull("createTime")) {//2014-12-09T09:21:39.000+08:00
							task.setPubDate(WfUtil.parseJsonDate(taskObj.getString("createTime")));
						}
						task.setAuthor(taskObj.getString("assignee"));
						task.setStep(taskObj.getString("name"));//例如：
						//task.setPubDate(taskObj.getString("createTime"));
						task.setTitle(taskObj.getString("name"));
						task.setCatalog(catalog);
						
						todo.getTodolist().add(task);
					}
				}
			}
			
			return todo;
			
		} catch (JSONException e) {
			throw AppException.json(e);
		} finally {
			inputStream.close();
		}
		
	}
	
}
